using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using UnityEngine;
using System.Collections.Generic;

namespace IQIGame.Onigao.GamePlay
{
    public class MainCitySceneCtrl : TSceneController<MainCitySceneLoader>, ISceneBlockAdapter
    {
        public MainCityRegionCtrl regionCtrl => parent as MainCityRegionCtrl;
        public SceneBlockController blockController { get; private set; }

        protected override void OnModuleGameplayInit()
        {
#if UNITY_EDITOR
            EditorBehaviourHelper.AddApplicationQuitEvent(ClearEntityDriverEnvironment);
#endif
        }

        protected override void OnSceneLoaded()
        {
            EntityDriverEnvironment.Instance.defaultGroundId = regionCtrl.cfgScene.DefaultGround;
            skybox?.SetTimeHour24(GameDataCenter.ClientDisplayTime.Hour);
        }

        public void ClearEntityDriverEnvironment()
        {
            EntityDriverEnvironment.Instance.Clear();
#if UNITY_EDITOR
            EditorBehaviourHelper.RemoveApplicationQuitEvent(ClearEntityDriverEnvironment);
#endif
        }

        public async UniTask EnterScene()
        {
            //必须添加到预加载，否则loadingUI会提前关闭（await LoadScene结束后loadingUI就会立即关闭）
            _loaderProcess.AddAsyncPreload(UpdateBlockOnEnterScene);
            await LoadScene(regionCtrl.cfgScene.SceneName);
        }

        #region 地图分块加载

        /// <summary>
        /// 进入场景后第一次加载分块
        /// 最后一个加载，因为不知道角色位置，所以需要服务器告诉位置后才能加载
        /// </summary>
        /// <returns></returns>
        private async UniTask UpdateBlockOnEnterScene()
        {
            //开始分块加载
            var cfgScene = regionCtrl.cfgScene;
            if (!cfgScene.BlockLoad)
            {
                return;
            }

            SceneBlockConfig sceneBlockConfig = new SceneBlockConfig()
            {
                sceneName = cfgScene.SceneName,
                sizeX = cfgScene.BlockCountX,
                sizeY = cfgScene.BlockCountZ,
                sceneRoot = new GameObject("SceneMap").transform,
                offsetPosition = cfgScene.BlockOffset.ToVector2(),
            };
            blockController = new SceneBlockController(this, sceneBlockConfig, OnBlockChanged);

            await blockController.LoadSceneBlockOnceAsync(GetCenterPosition());
        }

        public Vector3 GetCenterPosition()
        {
            var mainCharacter = regionCtrl.entityCtrl.playerAvatarEntity;
            if (mainCharacter != null)
            {
                return mainCharacter.transform.position;
            }
            return Vector3.zero;
        }

        /// <summary>
        /// 分块加载变化后对分块预设内的一些资源进行特殊处理，没有则不实现
        /// </summary>
        /// <param name="isToRemoved"></param>
        /// <param name="blockGameObject"></param>
        private void OnBlockChanged(bool isToRemoved, GameObject blockGameObject)
        {

        }
        #endregion

        protected override void OnUpdate(float deltaTime)
        {
            base.OnUpdate(deltaTime);

            if (blockController != null)
            {
                blockController.Update(deltaTime);
            }
        }

        protected override void OnDispose()
        {
            ClearEntityDriverEnvironment();
            if (blockController != null)
            {
                blockController.Dispose();
                blockController = null;
            }
        }
    }
}
